import {Component, OnInit, Input, ViewChild, ElementRef, Renderer, Output, EventEmitter} from '@angular/core';
import {Device} from '../../../entity/device.model';
import {Tag} from '../../../entity/tag.model';
import {ApplicationService} from '../../../service/application.service';
import {Farm} from '../../../entity/farm.model';
import {TagGroupItem} from './tag-group-item';
import {FarmCategoryEnum} from './farm-category.enum';
import {DeviceCategoryEnum} from './device-category.enum';
import {DeviceGroupItem} from './device-group-item';
import {List} from 'linqts';
import {ModelService} from '../../../service/model.service';
import {DeviceGroupCategoryEnum} from './device-selector/device-selector.component';

// import { Subject } from 'rxjs/Subject';


@Component({
  selector: 'app-device-tag-selector',
  templateUrl: './device-tag-selector.component.html',
  styleUrls: ['./device-tag-selector.component.css']
})
export class DeviceTagSelectorComponent implements OnInit {
  /**
   * 是否包含测点选择组件
   * 默认：false 不包含
   *
   * @memberof DeviceTagSelectorComponent
   */
  @Input() includeTagSelector = false;
  /**
   * 电站类别
   * 默认:FarmCategoryEnum.winfarm 风场
   * @type {FarmCategory}
   * @memberof DeviceSelectorComponent
   */
  @Input() farmCategory: FarmCategoryEnum;
  /**
   * 设备类别
   * 默认:DeviceCategoryEnum.turbine 风机
   * @type {DeviceCategoryEnum}
   * @memberof DeviceSelectorComponent
   */
  @Input() deviceCategories: DeviceCategoryEnum[] = [];
  /**
   * 被选中的电站
   * 默认:null
   * @type {Farm}
   * @memberof DeviceSelectorComponent
   */
  @Input() selectedFarm: Farm = null;
  /**
   * 被选中的电站
   * 默认:null
   * @type {Farm}
   * @memberof DeviceSelectorComponent
   */
  @Input() selectedFarmId: Number = 0;
  /**
   * 是否展示分组工具条
   *
   * @type {boolean}
   * @memberof DeviceSelectorComponent
   */
  @Input() displayGroupToolbar = true;
  /**
   * 限制设备选择数量
   * 默认:null 不做限制
   * 0不选择
   * @type {number}
   * @memberof DeviceSelectorComponent
   */
  @Input() choiceDeviceCount;
  /**
   *刚进页面是默认选择风机数量
   *默认:null 不做限制
   * 0不选择
   * @memberof DeviceTagSelectorComponent
   */
  @Input() defaultChooseDeviceCount;
  /**
   *在只能选择一个风场情况下，点击不同风场风机
   *清除之前选择风机为true
   *提示只能选择一个风场为false
   *默认为false
   * @memberof DeviceTagSelectorComponent
   */
  @Input() isClearSelectDevice = false;
  /**
   * 限制多选风场
   * 默认：false
   * false不允许多选
   * @type {boolean}
   * @memberof DeviceSelectorComponent
   */
  @Input() multipleFarm = true;
  /**
   * 限制多选设备
   * 默认：true
   * false不允许多选
   * @type {boolean}
   * @memberof DeviceSelectorComponent
   */
  @Input() multipleDevice = true;
  /**
   * 限制多选型号
   * 默认：false
   * false不允许多选
   * @type {boolean}
   * @memberof DeviceSelectorComponent
   */
  @Input() multipleModel = true;

  /**
   * 默认被选中的测点
   *
   * @type {Tag[]}
   * @memberof TagSelectorComponent
   */
  @Input() selectTages: any[] = [];
  /**
   * 限制测点选择数量
   *
   *
   * 默认:0
   * 0不做限制
   * @type {number}
   * @memberof DeviceSelectorComponent
   */
  @Input() choiceTagCount = 0;
  /**
   * 设置测点可用于那个模块
   * 默认：0
   * 趋势图  01
   * 矩阵  02
   * 结构图  03
   * 风机数据  04
   * 温度测点 05
   * @memberof TagSelectorComponent
   */
  @Input() tagSet = 0;
  /**
   * 被选中设备
   * 默认:null
   * @type {Farm}
   * @memberof DeviceSelectorComponent
   */
  @Input() selectedDevice: Device = null;

  /**
   * 被选中的设备Id
   *
   * @memberof DeviceSelectorComponent
   */
  @Input() selectedDeviceId = 0;
  /**
   *
   *
   * @memberof DeviceTagSelectorComponent
   */
  @Input() selectedTagAll = false;
  /**
   *分组默认选中
   *
   * @type {DeviceGroupCategoryEnum}
   * @memberof DeviceTagSelectorComponent
   */
  @Input() deviceGroupCategory: DeviceGroupCategoryEnum;
  /**
   *默认只选择一条线路
   *
   * @type {boolean}
   * @memberof DeviceTagSelectorComponent
   */
  @Input() selectAGroup: boolean;
  /**
   * 选中的设备
   *
   * @memberof DeviceSelectorComponent
   */
  @Output() selectedDevicesChange = new EventEmitter<Device[]>();
  /**
   * 选中的测点
   *
   * @memberof DeviceSelectorComponent
   */
  @Output() selectedTagsChange = new EventEmitter<Tag[]>();


  public dispalyDeviceGroups: DeviceGroupItem[] = [];
  public dispalyTagGroups: TagGroupItem[] = [];
  public removeDevice: Device = null;
  public removeTag: Tag = null;
  public modelIds: number[] = null;
  public deviceCategoryName = '设备';
  public dispalyDeviceSelector = false;
  public dispalyTagSelector = false;
  private timerOut: any = null;


  /**
   * Creates an instance of DeviceTagSelectorComponent.
   * @param {ApplicationService} application 全局运用缓存
   * @memberof DeviceTagSelectorComponent
   */
  constructor(
    private renderer: Renderer,
    private modelService: ModelService
  ) {
  }

  ngOnInit() {
  }

  onDeviceSelectorMouseEnter(elementEvent: Event) {
    this.timerOut = setTimeout(() => {
      this.dispalyDeviceSelector = true;
      clearTimeout(this.timerOut);
      this.timerOut = null;
    }, 200);
    // 阻止了事件冒泡，不会触发"#inner, body"的点击事件
    elementEvent.stopPropagation();
  }

  onDeviceSelectorMouseLeave(elementEvent: any) {
    let userAgent = navigator.userAgent;
    if (userAgent.indexOf('Firefox') > -1) {
      this.dispalyDeviceSelector = false;
    } else {
      // 这个判断是为了防止意外关闭
      if (elementEvent.toElement) {
        if (this.timerOut) {
          clearTimeout(this.timerOut);
          this.timerOut = null;
        }
        this.dispalyDeviceSelector = false;
      }
    }

    // 阻止了事件冒泡，不会触发"#inner, body"的点击事件
    elementEvent.stopPropagation();
  }

  onSelectedDevicesChange(devices: Device[]) {
    this.dispalyDeviceGroups = [];
    this.modelIds = null;
    if (devices != null && devices.length > 0) {
      const ids: number[] = [];
      const list = new List(devices);
      const group = list.GroupBy(grouper => grouper.farmName, mapper => mapper);
      const farmNames = Object.getOwnPropertyNames(group);
      farmNames.forEach(farmName => {
        const farmDivices: Device[] = Object.getOwnPropertyDescriptor(group, farmName).value;
        this.dispalyDeviceGroups.push({
          title: farmName,
          isChecked: false,
          devices: farmDivices,
        });
        if (this.includeTagSelector === true) {
          if (farmDivices != null && farmDivices.length > 0) {
            farmDivices.forEach(device => {
              if (ids.findIndex(id => id === device.modelId) === -1) {
                ids.push(device.modelId);
              }
            });
          }
        }
      });
      this.modelIds = ids;
      this.selectedDevicesChange.emit(devices);
    } else {
      // 于春强添加，当不选择设备时显示全部测点
      this.modelService.getModelWithFactory()
        .then(res => {
          if (!res) return false;
          this.modelIds = [...res.map(o => o.modelId)];
        })
        .catch(err => {
          console.log(err)
        });
      this.selectedDevicesChange.emit([]);
    }
  }

  onRemoveDevice(device: Device) {
    this.dispalyDeviceGroups.forEach(group => {
      const index = group.devices.findIndex(o => o.deviceId === device.deviceId);
      if (index !== -1) {
        group.devices.splice(index, 1);
        // 跳出循环
        return;
      }
    });
    // 通知设备选择组件移除设备选中状态
    this.removeDevice = device;
    // 触发设备选中变更事件
    const emitDevices: Device[] = [];
    this.dispalyDeviceGroups.forEach(group => {
      if (group.devices.length > 0) {
        emitDevices.push(...group.devices);
      }
    });
    this.selectedDevicesChange.emit(emitDevices);
  }

  onTagSelectorMouseEnter(elementEvent: Event) {
    this.timerOut = setTimeout(() => {
      this.dispalyTagSelector = true;
      clearTimeout(this.timerOut);
      this.timerOut = null;
    }, 200);
    // 阻止了事件冒泡，不会触发"#inner, body"的点击事件
    elementEvent.stopPropagation();
  }

  onTagSelectorMouseLeave(elementEvent: any) {
    // 这个判断是为了防止意外关闭
    if (elementEvent.toElement) {
      if (this.timerOut) {
        clearTimeout(this.timerOut);
        this.timerOut = null;
      }
      this.dispalyTagSelector = false;
    }
    // 阻止了事件冒泡，不会触发"#inner, body"的点击事件
    elementEvent.stopPropagation();
  }

  onSelectedTagsChange(tags: Tag[]) {
    this.dispalyTagGroups = [];
    if (tags != null && tags.length > 0) {
      const list = new List(tags);
      const group = list.GroupBy(grouper => grouper.turbComponentName, mapper => mapper);
      const turbComponentNames = Object.getOwnPropertyNames(group);
      turbComponentNames.forEach(turbComponentName => {
        const turbComponentTag = Object.getOwnPropertyDescriptor(group, turbComponentName).value;
        this.dispalyTagGroups.push({
          title: turbComponentName,
          turbComponentId: 0,
          isChecked: false,
          tags: turbComponentTag,
        });
      });
      this.selectedTagsChange.emit(tags);
    } else {
      this.selectedTagsChange.emit([]);
    }
  }

  onRemoveTag(tag: Tag) {
    this.dispalyTagGroups.forEach(group => {
      const index = group.tags.findIndex(o => o.tagId === tag.tagId);
      if (index !== -1) {
        group.tags.splice(index, 1);
        // 跳出循环
        return;
      }
    });
    // 通知测点选择组件移除测点选中状态
    this.removeTag = tag;
    // 触发测点选中变更事件
    const emitTags: Tag[] = [];
    this.dispalyTagGroups.forEach(group => {
      if (group.tags.length > 0) {
        emitTags.push(...group.tags);
      }
    });
    this.selectedTagsChange.emit(emitTags);
  }
}
